package com.framework.base.aqs;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chaolong.jin
 * @description
 * @date 2019/08/24 22:09
 */
public class H2O {
    private Lock lock = new ReentrantLock();
    private Condition hCondition = lock.newCondition();
    private Condition oCondition = lock.newCondition();
    private static BlockingQueue h = new ArrayBlockingQueue(2);
    private static BlockingQueue o = new ArrayBlockingQueue(1);
    private static AtomicInteger hTom = new AtomicInteger(0);
    private static AtomicInteger oTom = new AtomicInteger(0);
    private static CyclicBarrier hBarrier = new CyclicBarrier(2);
    private static CyclicBarrier oBarrier = new CyclicBarrier(1);
    private static Integer count = 0;
    private static Semaphore hSemapHore = new Semaphore(2);
    private static Semaphore oSemapHore = new Semaphore(2);

    public static void main(String[] args) {
        int n = 5;
        new Thread(new Hthread(n)).start();
        new Thread(new Othread(n)).start();
    }

    static class Hthread implements Runnable {
        private int n;

        public Hthread(int n) {
            this.n = n;
        }

        @Override
        public void run() {

            while (n > 0) {
                try {
                    hSemapHore.acquire(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                n--;
                System.out.print("H");
                oSemapHore.release(1);
            }


        }

    }

    static class Othread implements Runnable {
        private int n;

        public Othread(int n) {
            this.n = n;
        }

        @Override
        public void run() {
            while (n > 0) {
                try {
                    oSemapHore.acquire(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                n--;

                System.out.print("O");
                hSemapHore.release(2);
            }
        }
    }
}
